package freespiritsocial.io.user.ui.fragment

import android.os.Bundle
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.get
import androidx.fragment.app.Fragment
import com.google.firebase.database.*
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.data.TabEntity
import freespiritsocial.io.user.databinding.FrgMainBinding
import freespiritsocial.io.user.ui.activity.MainAct
import freespiritsocial.io.user.ui.fragment.home.HomeFrg
import freespiritsocial.io.user.ui.fragment.message.MessageFrg
import freespiritsocial.io.user.ui.fragment.mine.MineFrg
import freespiritsocial.io.user.ui.fragment.post.PostDetailFrg
import freespiritsocial.io.user.ui.fragment.search.SearchFrg
import freespiritsocial.io.user.viewmodel.MainViewModel
import freespiritsocial.io.user.weight.tablayout.listener.CustomTabEntity
import freespiritsocial.io.user.weight.tablayout.listener.OnTabSelectListener
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

/**
 * @author csw
 * @date 2021-10-17
 */
class MainFrg: BaseFragment<MainViewModel,FrgMainBinding>(),OnTabSelectListener {

    private val mIconSelectIds = intArrayOf(
        R.mipmap.tab_select_home,R.mipmap.tab_select_search,
        R.color.white,R.mipmap.tab_select_message,-1
    )
    private val mIconUnselectIds = intArrayOf(
        R.mipmap.tab_unselect_home,R.mipmap.tab_unselect_search,
        R.color.white,R.mipmap.tab_unselect_message,-1
    )
    private val mTabEntities by lazy(LazyThreadSafetyMode.NONE) {
        arrayListOf<CustomTabEntity>().apply {
            for (i in mIconSelectIds.indices) {
                add(TabEntity("",mIconSelectIds[i],mIconUnselectIds[i]))
            }
        }
    }

    private val isReadStatus: DatabaseReference by lazy {
        FirebaseDatabase.getInstance("https://freespirit-323804.firebaseio.com/").getReference("${appViewModel.userinfo.value?.userId}")
    }

    private val isReadListener by lazy {
        object: ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {
                (p0.value as? HashMap<*,*>)?.let {
                    val isRead = it.getOrDefault("isRead",false)
                    val user = appViewModel.userinfo.value
                    user?.isRead = isRead as Boolean
                    appViewModel.userinfo.postValue(user)
                }
            }

            override fun onCancelled(p0: DatabaseError) {}
        }
    }

    private val mFragments by lazy(LazyThreadSafetyMode.NONE) {
        arrayListOf(HomeFrg(),SearchFrg(),Fragment(),MessageFrg(),MineFrg())
    }

    override fun layoutId(): Int = R.layout.frg_main

    override fun initView(savedInstanceState: Bundle?) = with(mDatabind) {
        click = Click()
        tab.setTabData(mTabEntities,requireActivity(),R.id.fl_fragment,mFragments)
        //屏蔽 第三个tab触摸
        (tab[0] as? ViewGroup)?.get(2)?.isEnabled = false
        tab.setOnTabSelectListener(this@MainFrg)
    }

    override fun lazyLoadData() {
        mViewModel.getUserInfo {
            appViewModel.chatConnectStatus.postValue(it)
        }
        mViewModel.getNotificationSetting()
        mViewModel.getFirebase {
            isReadStatus.addValueEventListener(isReadListener)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isReadStatus.removeEventListener(isReadListener)
    }

    override fun createObserver() {
        super.createObserver()
        (activity as MainAct).curPostId.observe(this) {
            val id = it ?: return@observe
            mViewModel.getPost(id) {
                nav().navigateAction(
                    R.id.postDetailFrg,
                    bundle = bundleOf(PostDetailFrg.KEY_DATA to it)
                )
            }
        }
        eventViewModel.changeMainTag.observe(this) {
            mDatabind.tab.currentTab = it
            if (it == 0) {
                (mFragments[0] as HomeFrg).switchPage(1,true)
            }
        }
        eventViewModel.hasUnReadMessage.observe(this) {
            val lastIndex = mTabEntities.lastIndex
            if (it)
                mDatabind.tab.showDot(lastIndex - 1)
            else
                mDatabind.tab.hideMsg(lastIndex - 1)
        }
        appViewModel.userinfo.observe(this) {
            it ?: return@observe
            mDatabind.tab.setImageTabUrl(it.userAvatar)
            if (it.isRead) {
                mDatabind.tab.showDot(4)
            } else {
                mDatabind.tab.hideMsg(4)
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not()) (mFragments[0] as HomeFrg).onReShow()
    }

    inner class Click {
        fun add() {
            nav().navigateAction(R.id.action_mainFrg_to_editPostFrg)
        }

    }

    override fun onTabSelect(position: Int) {
        if (position == 1) {
            // FIXME: 2022/1/21 互相伤害
            (mFragments[position] as SearchFrg).mViewModel.clear()
        }
    }

    override fun onTabReselect(position: Int) {
    }
}